package com.xujie.chat.server.handler;

import com.xujie.chat.message.MessageType;
import com.xujie.chat.message.MsgHeader;
import com.xujie.chat.message.MyMessage;
import com.xujie.chat.server.manager.ClientManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Xujie
 * @since 2024/12/28 18:15
 **/


public class AuthHandler extends ChannelInboundHandlerAdapter {
	private final Logger log = LoggerFactory.getLogger(AuthHandler.class);

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

		MyMessage message = (MyMessage) msg;
		MsgHeader msgHeader = message.getMyHeader();
		if (msgHeader != null && msgHeader.getType() == MessageType.LOGIN_REQ.value()) {
			log.debug("认证消息: {}", msg);
			ChannelId id = ctx.channel().id();

			String longText = id.asLongText();
			log.debug("认证成功：{}", longText);
			// 添加到已认证的channel
			String clientId = ClientManager.addClient(ctx.channel());
			ctx.writeAndFlush(buildResponse(clientId));
			ReferenceCountUtil.release(msg);

		} else {
			ctx.fireChannelRead(msg);
		}
	}

	private MyMessage buildResponse(String result) {
		MyMessage message = new MyMessage();
		MsgHeader msgHeader = new MsgHeader();
		msgHeader.setType(MessageType.LOGIN_RESP.value());
		message.setMyHeader(msgHeader);
		message.setBody(result);
		return message;
	}

}
